package com.huayun.plugin.flightSimulation.service;

import com.huayun.plugin.flightSimulation.dao.FlightSimulationRepository;
import com.huayun.plugin.flightSimulation.domain.FlightSimulation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class FlightSimulationService {
    @Autowired
    private final FlightSimulationRepository flightSimulationRepository;

    public FlightSimulationService(FlightSimulationRepository flightSimulationRepository) {
        this.flightSimulationRepository = flightSimulationRepository;
    }

    public String saveXML(String assemblyFid, String assemblyFName, String xmlFid, MultipartFile xmlFile){
        FlightSimulation flightSimulation = new FlightSimulation();
        //向数据库添加材料信息
        flightSimulation.setAssemblyFid(assemblyFid);
        flightSimulation.setAssemblyFName(assemblyFName);
        flightSimulation.setXmlFid(xmlFid);
        flightSimulation.setCreateTime(new Date());
        try {
            flightSimulation.setXmlFile(new String(xmlFile.getBytes()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        flightSimulationRepository.save(flightSimulation);
        return "文件上传并保存成功";
    }
    public FlightSimulation searchSavedXMLAssemInfo(String assemblyFid){
        List<FlightSimulation> flightSimulationList = flightSimulationRepository.findByAssemblyFid(assemblyFid);
        if (flightSimulationList == null || flightSimulationList.isEmpty()) {
            return null;
        }
        flightSimulationList.sort(Comparator.comparing(FlightSimulation::getCreateTime).reversed());
        return flightSimulationList.get(0);
    }
}
